package com.yunshang.ys.ui.tab1;

import android.animation.ValueAnimator;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.yunshang.ys.R;
import com.yunshang.ys.base.BaseFragment;
import com.yunshang.ys.sql.RecordSQLiteOpenHelper;
import com.yunshang.ys.ui.tab1.fragment.Tab1fragment;
import com.yunshang.ys.ui.tab1.tabview.TabPagerIndicator;
import com.yunshang.ys.ui.tab1.tabview.TabVPAdapter;
import com.yunshang.ys.utils.ComplexUtil;
import com.yunshang.ys.utils.ScreenUtil;
import com.yunshang.ys.view.SearchListview;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/6/27.
 */

public class MainFragment0 extends BaseFragment {


    private View viewContent;
    private TabPagerIndicator tabPagerIndicator;
    ViewPager viewPager;
    private List<Fragment> fragments;
    private List<String> tabTitles;


    //    TextView tvsearch;
    TextView tveye;
    LinearLayout llsearch;
    private boolean llshow;
    private EditText etsearch;
    private PopupWindow popmenu;
    private View popview;
    private TextView tvClear;
    private RecordSQLiteOpenHelper sqlhelper;
    private SearchListview lvHistory;
    private SimpleCursorAdapter lvadapter;
    private SQLiteDatabase db;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        viewContent = inflater.inflate(R.layout.fragment_main0, null);
        return viewContent;

    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

//        tvsearch = (TextView) view.findViewById(R.id.et_mainsearch);
//        tvsearch.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                Toast.makeText(getActivity(), "search", Toast.LENGTH_SHORT).show();
//            }
//        });


        fragments = new ArrayList<>();
        tabTitles = new ArrayList<>();
        tabTitles.add("ttttttt " + 0);
        tabTitles.add("ttttt " + 1);
        tabTitles.add("ttt " + 2);
        tabTitles.add("t " + 3);
        tabTitles.add("ttttttttt " + 4);
        for (int i = 0; i < 5; i++) {
            fragments.add(new Tab1fragment());
        }
        tabPagerIndicator = (TabPagerIndicator) viewContent.findViewById(R.id.pagerIndicator);
        viewPager = (ViewPager) viewContent.findViewById(R.id.viewPager);
        viewPager.setAdapter(new TabVPAdapter(getChildFragmentManager(), fragments, tabTitles));
        tabPagerIndicator.setViewPager(viewPager);


        llsearch = (LinearLayout) view.findViewById(R.id.ll_search);
        etsearch = (EditText) view.findViewById(R.id.et_mainsearch);
        tveye = (TextView) view.findViewById(R.id.tv_eye);
        final int dimensionPixelSize = getResources().getDimensionPixelSize(R.dimen.y90);
        final int screenWidth = ScreenUtil.getScreenWidth(getActivity());
        final int width = llsearch.getWidth();
        tveye.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                performAnim2(0, screenWidth);

//                popmenu.showAsDropDown(tveye);
            }
        });
        //搜索框的文本变化实时监听
        etsearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            //输入后调用该方法
            @Override
            public void afterTextChanged(Editable s) {

                if (s.toString().trim().length() == 0) {
                    //若搜索框为空,则模糊搜索空字符,即显示所有的搜索历史
                } else {
                }

                //每次输入后都查询数据库并显示
                //根据输入的值去模糊查询数据库中有没有数据
                String tempName = etsearch.getText().toString();
                queryData(tempName);    // 时时改变

            }
        });
        // 搜索框的键盘搜索键
        // 点击回调
        etsearch.setOnKeyListener(new View.OnKeyListener() {// 输入完后按键盘上的搜索键
            // 修改回车键功能
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                    // 隐藏键盘，这里getCurrentFocus()需要传入Activity对象，如果实际不需要的话就不用隐藏键盘了，免得传入Activity对象，这里就先不实现了
//                    ((InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(
//                            getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);

                    // 按完搜索键后将当前查询的关键字保存起来,如果该关键字已经存在就不执行保存
                    String trim = etsearch.getText().toString().trim();
                    if (!TextUtils.isEmpty(trim)) {
//                        popmenu.showAsDropDown(llsearch);
                        boolean hasData = hasData(trim);
                        if (!hasData) {
                            insertData(trim);
                            queryData("");
                        }
                        //根据输入的内容模糊查询商品，并跳转到另一个界面，这个需要根据需求实现
                    }
                    Toast.makeText(ComplexUtil.getmApplicationContent(), "点击搜索", Toast.LENGTH_SHORT).show();
                }
                return false;
            }
        });
//        etsearch.setOnFocusChangeListener(new View.OnFocusChangeListener() {
//            @Override
//            public void onFocusChange(View v, boolean hasFocus) {
//                if (hasFocus)
//            }
//        });


        sqlhelper = new RecordSQLiteOpenHelper(ComplexUtil.getmApplicationContent());
//        popview = View.inflate(ComplexUtil.getmApplicationContent(), R.layout.pop_search_history, null);
        lvHistory = (SearchListview) view.findViewById(R.id.lv_history);

        // 第一次进入时查询所有的历史记录
        queryData("");

        //列表监听
        //即当用户点击搜索历史里的字段后,会直接将结果当作搜索字段进行搜索
        lvHistory.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //获取到用户点击列表里的文字,并自动填充到搜索框内
                TextView textView = (TextView) view.findViewById(android.R.id.text1);
                String name = textView.getText().toString();
                etsearch.setText(name);
                Toast.makeText(ComplexUtil.getmApplicationContent(), name, Toast.LENGTH_SHORT).show();
            }
        });

        tvClear = (TextView) view.findViewById(R.id.tv_clear_history);
        tvClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            //清空数据库
                deleteData();
                queryData("");
            }
        });
//        popmenu = new PopupWindow(popview, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, false);
//        popmenu.setOutsideTouchable(true);
////        popmenu.setFocusable(true);
//        popmenu.setBackgroundDrawable(new BitmapDrawable(getResources(), (Bitmap) null));

    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        if (!hidden) {
            System.out.println("0");
//            Toast.makeText(ComplexUtil.getmApplicationContent(), "0", Toast.LENGTH_SHORT).llshow();
        }
        super.onHiddenChanged(hidden);
    }

    public int getTabPagerIndicator() {
        return tabPagerIndicator.getHeight();
    }


    private  void performAnim2(int from, int width) {
        //View是否显示的标志
        llshow = !llshow;
        //属性动画对象
        ValueAnimator va;
        if (llshow) {
            tvClear.setVisibility(View.VISIBLE);
            lvHistory.setVisibility(View.VISIBLE);
            //显示view，高度从0变到height值
            va = ValueAnimator.ofInt(from, width);
        } else {
            tvClear.setVisibility(View.GONE);
            lvHistory.setVisibility(View.GONE);
            //隐藏view，高度从height变为0
            va = ValueAnimator.ofInt(width, from);
        }
        va.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                //获取当前的height值
                int w = (Integer) valueAnimator.getAnimatedValue();
                //动态更新view的高度
                llsearch.getLayoutParams().width = w;
                llsearch.requestLayout();
            }
        });
        va.setDuration(1000);
        //开始动画
        va.start();
    }


    /*清空数据*/
    private void deleteData() {
        db = sqlhelper.getWritableDatabase();
        db.execSQL("delete from records");
        db.close();
    }

    private void queryData(String tempName) {
        //模糊搜索
        Cursor cursor = sqlhelper.getReadableDatabase().rawQuery(
                "select id as _id,name from records where name like '%" + tempName + "%' order by id desc ", null);
        // 创建adapter适配器对象,装入模糊搜索的结果
        lvadapter = new SimpleCursorAdapter(ComplexUtil.getmApplicationContent(),
                android.R.layout.simple_list_item_1, cursor, new String[]{"name"},
                new int[]{android.R.id.text1}, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
        // 设置适配器
        lvHistory.setAdapter(lvadapter);
        lvadapter.notifyDataSetChanged();
    }
    /*插入数据*/
    private void insertData(String tempName) {
        db = sqlhelper.getWritableDatabase();
        db.execSQL("insert into records(name) values('" + tempName + "')");
        db.close();
    }
    /*检查数据库中是否已经有该条记录*/
    private boolean hasData(String tempName) {
        //从Record这个表里找到name=tempName的id
        Cursor cursor = sqlhelper.getReadableDatabase().rawQuery(
                "select id as _id,name from records where name =?", new String[]{tempName});
        //判断是否有下一个  //(判断是否有第一个)
        return cursor.moveToNext();
    }


}
